/*
 * @Author: 徐建辰
 * @Date: 2022-02-12 15:08:14
 * @LastEditTime: 2022-02-16 15:36:02
 * @LastEditors: 徐建辰
 * @Description: 二次封装axios
 */
import axios from 'axios'
import {Toast} from 'vant'
import router from '@/router'
import {getToken, removeToken} from '@/utils/local'
import {httpUrl} from '@/utils/constant'

axios.defaults.baseURL = httpUrl
axios.defaults.withCredentials = true
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers['token'] = getToken() || ''
axios.defaults.headers.post['Content-Type'] = 'application/json'

// 响应拦截
axios.interceptors.response.use(res => {
  // console.log('res.data-------',res.data);
  // console.log(typeof res.data)
  if (typeof res.data !== 'object') {
    Toast.fail('服务端异常！')
    return Promise.reject(res)
  }
  if (res.data.resultCode !== 200) {
    const {message, resultCode} = res.data
    message && Toast.fail(message)
    if (resultCode === 416) {
      removeToken()
      // 需要重新登录
      router.replace({path: '/login'})
    }
    if (res.data.data && window.location.hash == '#/login') {
      const token = res.data.data
      setToken(token)
      axios.defaults.headers['token'] = token
    }
    return Promise.reject(res)
  }

  return res.data
}, err => {
  console.log(err)
})

export default axios